#include "push_predis.h"

extern void push_db_data(string addr, string query, string error, long execute_micro_time);

void push_predis_handler(zend_execute_data *execute_data, long execute_micro_time, string class_name, string function_name)
{
    uint32_t arg_count = ZEND_CALL_NUM_ARGS(execute_data);
    if (arg_count)
    {
        // 初始化参数
        string operate = "";
        string key = "";
        string ip = "";
        string port = "";
        string addr = "";
        string err = "";
        string query = "";

        zval *connection = read_obj_property(&(execute_data->This), "connection", "Predis\\Connection\\StreamConnection");
        if (connection == nullptr)
        {
            return;
        }
        zval *parameters = read_obj_property(connection, "parameters", "Predis\\Connection\\Parameters");
        if (parameters == nullptr)
        {
            return;
        }
        zval *params = read_property(parameters, "parameters");
        zval *z_host = zend_hash_str_find(Z_ARRVAL_P(params), "host", sizeof("host") - 1);
        zval *z_port = zend_hash_str_find(Z_ARRVAL_P(params), "port", sizeof("port") - 1);
        zval z_port_o;
        ZVAL_COPY(&z_port_o, z_port);
        ip = ZSTR_VAL(Z_STR_P(z_host));
        convert_to_long(&z_port_o);
        port = to_string(Z_LVAL(z_port_o));
        addr = ip + ":" + port;

        // 获取函数传参
        uint32_t arg_count = ZEND_CALL_NUM_ARGS(execute_data);
        if (arg_count)
        {
            zval *id = ZEND_CALL_ARG(execute_data, 1);
            if (Z_TYPE_P(id) == IS_STRING)
            {
                operate = Z_STRVAL_P(id);
            }
        }

        // zval *id = (zval *)emalloc(sizeof(zval));
        // zval *arguments = (zval *)emalloc(sizeof(zval));

        // zend_call_method(command, Z_OBJCE_P(command), nullptr, ZEND_STRL("getid"), id, 0, nullptr, nullptr);
        // zend_call_method(command, Z_OBJCE_P(command), nullptr, ZEND_STRL("getarguments"), arguments, 0, nullptr, nullptr);

        // if (id != nullptr && Z_TYPE_P(id) == IS_STRING)
        // {
        //     operate = Z_STRVAL_P(id);
        // }

        // if (arguments != nullptr && Z_TYPE_P(arguments) == IS_ARRAY)
        // {
        //     zval *z_key = zend_hash_index_find(Z_ARRVAL_P(arguments), 0);
        //     if (z_key != nullptr && Z_TYPE_P(z_key) == IS_STRING)
        //     {
        //         key = Z_STRVAL_P(z_key);
        //     }
        // }

        query = class_name + "->" + function_name + "::" + operate;// + "[" + key + "]";

        push_db_data(addr, query, err, execute_micro_time);
    }
}